package com.xuecheng.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.base.exception.CommonError;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.utils.JsonUtil;
import com.xuecheng.content.config.MultipartSupportConfig;
import com.xuecheng.content.feignclient.MediaServiceClient;
import com.xuecheng.content.mapper.*;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.CoursePreviewDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.content.service.CoursePublishService;
import com.xuecheng.content.service.CourseTeacherService;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.messagesdk.model.po.MqMessage;
import com.xuecheng.messagesdk.service.MqMessageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: Hes
 * @description 课程预览接口实现
 * @date: 2023/6/23 17:51
 */
@Slf4j
@Service
public class CoursePublishServiceImpl implements CoursePublishService {

    @Autowired
    CourseBaseInfoService courseBaseInfoService;

    @Autowired
    TeachplanService teachplanService;

    @Autowired
    CourseTeacherService courseTeacherService;

    @Autowired
    CoursePublishPreMapper coursePublishPreMapper;

    @Autowired
    CourseMarketMapper courseMarketMapper;

    @Autowired
    CourseBaseInfoMapper courseBaseInfoMapper;

    @Autowired
    CoursePublishMapper coursePublishMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    MqMessageService mqMessageService;

    @Autowired
    MediaServiceClient mediaServiceClient;

    @Autowired
    RedissonClient redissonClient;

    /**
     * 课程预览
     *
     * @param courseId
     * @return
     */
    @Override
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) {
        CourseBaseInfoDto courseBaseInfoDto = courseBaseInfoService.getCourseBaseById(courseId);
        List<TeachplanDto> teachplanTree = teachplanService.findTeachplanTree(courseId);
        List<CourseTeacher> teachers = courseTeacherService.list(courseId);
        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        coursePreviewDto.setCourseBase(courseBaseInfoDto);
        coursePreviewDto.setTeachplans(teachplanTree);
        coursePreviewDto.setTeachers(teachers);
        return coursePreviewDto;
    }

    /**
     * 课程提交审核
     * <p>
     * 1、对已提交审核的课程不允许提交审核。
     * 2、本机构只允许提交本机构的课程。
     * 3、没有上传图片不允许提交审核。
     * 4、没有添加课程计划不允许提交审核。
     *
     * @param companyId
     * @param courseId
     */
    @Override
    @Transactional
    public void commitAudit(Long companyId, Long courseId) {
        CourseBase courseBase = courseBaseInfoMapper.selectById(courseId);
        String auditStatus = courseBase.getAuditStatus();
        if ("202003".equals(auditStatus)) {
            log.debug("该教程已提交，不能再次提交,courseId:{}", courseId);
            XueChengPlusException.cast("该教程已提交，不能再次提交");
            return;
        }
        if (!courseBase.getCompanyId().equals(companyId)) {
            log.debug("本机构只允许提交本机构的课程,companyId:{}", companyId);
            XueChengPlusException.cast("本机构只允许提交本机构的课程");
            return;
        }
        if (StringUtils.isEmpty(courseBase.getPic())) {
            log.debug("请补充课程的图片,courseId:{}", courseId);
            XueChengPlusException.cast("请补充课程的图片");
            return;
        }
        //查询师资信息
        List<TeachplanDto> teachplanTree = teachplanService.findTeachplanTree(courseId);
        if (teachplanTree.size() <= 0) {
            log.debug("课程没有课程计划，请补充课程计划,courseId:{}", courseId);
            XueChengPlusException.cast("课程没有课程计划，请补充课程计划");
            return;
        }
        //查询师资信息
        List<CourseTeacher> teachers = courseTeacherService.list(courseId);
        //传json
        String teachersJson = JsonUtil.listTojson(teachers);
        //查课程营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        //查询课程信息和营销信息
        CourseBaseInfoDto courseBaseInfoDto = courseBaseInfoService.getCourseBaseById(courseId);
        //把课程信息和营销信息拷贝到coursePublishPre
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        BeanUtils.copyProperties(courseBaseInfoDto, coursePublishPre);
        //营销信息传json
        String marketJSON = JSON.toJSONString(courseMarket);
        coursePublishPre.setMarket(marketJSON);
        //师资信息传json
        String teachplanJson = JsonUtil.listTojson(teachplanTree);
        //设置师资信息、教学计划信息
        coursePublishPre.setTeachplan(teachplanJson);
        coursePublishPre.setTeachers(teachersJson);
        //设置预发布记录状态,已提交
        coursePublishPre.setCreateDate(LocalDateTime.now());
        coursePublishPre.setStatus("202003");
        coursePublishPre.setCompanyId(companyId);
        CoursePublishPre coursePublishPreUpdate = coursePublishPreMapper.selectById(courseId);
        if (coursePublishPreUpdate == null) {
            coursePublishPreMapper.insert(coursePublishPre);
        } else {
            coursePublishPreMapper.updateById(coursePublishPre);
        }
        //更新课程信息表的审核和发布状态
        courseBase.setAuditStatus("202003");
        courseBase.setStatus("203001");
        courseBase.setChangeDate(LocalDateTime.now());
        courseBaseInfoMapper.updateById(courseBase);
    }

    /**
     * 课程发布、插入消息表、修改课程状态、删除预发布表
     *
     * @param companyId
     * @param courseId
     */
    @Override
    @Transactional
    public void coursepublish(Long companyId, Long courseId) {
        CourseBase courseBase = courseBaseInfoMapper.selectById(courseId);
        if (!companyId.equals(courseBase.getCompanyId())) {
            XueChengPlusException.cast("只有本机构可以发布课程");
        }
        //如果审核状态不是审核成功，或者发布状态是已发布
        if (!"202004".equals(courseBase.getAuditStatus()) || !"203001".equals(courseBase.getStatus())) {
            XueChengPlusException.cast("未审核成功，请检查发布状态");
        }
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        //判断预发布
        if (coursePublishPre == null || !"202004".equals(coursePublishPre.getStatus())) {
            XueChengPlusException.cast("先审核通过再发布课程");
        }
        //保存发布表
        saveCoursePublish(courseId);
        //保存消息表
        saveCoursePublishMessage(courseId);
        //删除预发布表
        coursePublishPreMapper.deleteById(courseId);

    }

    /**
     * freemarker页面静态化
     *
     * @param courseId
     * @return
     */
    @Override
    public File generateCourseHtml(Long courseId) {

        //静态化文件
        File htmlFile = null;

        //配置freemarker
        Configuration configuration = new Configuration(Configuration.getVersion());
        try {
            //加载模板
            //选指定模板路径,classpath下templates下
            //得到classpath路径
            String classpath = this.getClass().getResource("/").getPath();
            configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
            //设置字符编码
            configuration.setDefaultEncoding("utf-8");

            //指定模板文件名称
            Template template = configuration.getTemplate("course_template.ftl");

            //准备数据
            CoursePreviewDto coursePreviewInfo = getCoursePreviewInfo(40L);

            Map<String, Object> map = new HashMap<>();
            map.put("model", coursePreviewInfo);

            //静态化
            //参数1：模板，参数2：数据模型
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            System.out.println(content);
            //创建静态化文件
            htmlFile = File.createTempFile("course", ".html");
            //将静态化内容输出到文件中
            InputStream inputStream = IOUtils.toInputStream(content);
            //输出流
            FileOutputStream outputStream = new FileOutputStream(htmlFile);
            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            log.error("课程静态化异常:{}", e.toString());
            XueChengPlusException.cast("课程静态化异常");
        }

        return htmlFile;
    }

    /**
     * 静态页面上传minio
     *
     * @param courseId
     * @param file
     */
    @Override
    public void uploadCourseHtml(Long courseId, File file) {
        MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
        String s = mediaServiceClient.uploadFile(multipartFile, "course/" + courseId + ".html");
        if (StringUtils.isEmpty(s)) {
            XueChengPlusException.cast("静态化页面上传minio失败");
        }
    }

    /**
     * 学习中心远程调用
     *
     * @param courseId
     * @return
     */
    @Override
    public CoursePublish getCoursepublish(Long courseId) {
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
        return coursePublish;
    }

    /**
     * 从缓存中查询课程
     *
     * @param courseId
     * @return
     */
    @Override
//Redisson分布式锁
    public CoursePublish getCoursePublishCache(Long courseId) {
        //查询缓存
        String jsonString = (String) redisTemplate.opsForValue().get("course:" + courseId);
        if (StringUtils.isNotEmpty(jsonString)) {
            if (jsonString.equals("null")) {
                return null;
            }
            CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
            return coursePublish;
        } else {
            //每门课程设置一个锁
            RLock lock = redissonClient.getLock("coursequerylock:" + courseId);
            //获取锁
            lock.lock();
            try {
                jsonString = (String) redisTemplate.opsForValue().get("course:" + courseId);
                if (StringUtils.isNotEmpty(jsonString)) {
                    CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
                    return coursePublish;
                }
                System.out.println("=========从数据库查询==========");
                //从数据库查询
                CoursePublish coursePublish = getCoursepublish(courseId);
                redisTemplate.opsForValue().set("course:" + courseId, JSON.toJSONString(coursePublish), 1, TimeUnit.DAYS);
                return coursePublish;
            } finally {
                //释放锁
                lock.unlock();
            }
        }


    }


    //本地同步锁
//    @Override
//    public CoursePublish getCoursePublishCache(Long courseId) {
//        Object result = redisTemplate.opsForValue().get("course:" + courseId);
//        if (result != null) {
//            CoursePublish coursePublish = JSON.parseObject(result.toString(), CoursePublish.class);
//            return coursePublish;
//        } else {
//            synchronized (this) {
//                //在查一次缓存，可能在上一个线程写数据的时候下个线程进来了
//                Object resultObj = redisTemplate.opsForValue().get("course:" + courseId);
//                if (resultObj != null) {
//                    CoursePublish coursePublish = JSON.parseObject(resultObj.toString(), CoursePublish.class);
//                    return coursePublish;
//                }
//                log.debug("从数据库查");
//                CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
//                redisTemplate.opsForValue().set("course:" + courseId, JsonUtil.objectTojson(coursePublish), 300, TimeUnit.SECONDS);
//                return coursePublish;
//            }
//        }
//
//    }
//    @Override
//    public CoursePublish getCoursePublishCache(Long courseId) {
//        Object result = redisTemplate.opsForValue().get("course:" + courseId);
//        if (result != null) {
//            CoursePublish coursePublish = JSON.parseObject(result.toString(), CoursePublish.class);
//            return coursePublish;
//        } else {
//            log.debug("从数据库查");
//            CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
//            redisTemplate.opsForValue().set("course:" + courseId, JsonUtil.objectTojson(coursePublish),300, TimeUnit.SECONDS);
//            return coursePublish;
//        }
//
//    }

    /**
     * 保存消息表
     *
     * @param courseId
     */
    public void saveCoursePublishMessage(Long courseId) {
//        MqMessage mqMessage = new MqMessage();
//        mqMessage.setMessageType("course_publish");
//        mqMessage.setBusinessKey1(String.valueOf(courseId));
//        mqMessageMapper.insert(mqMessage);
        //保存消息表,引入消息sdk，上边可以替换成下边的
        MqMessage course_publish = mqMessageService.addMessage("course_publish",
                String.valueOf(courseId),
                null,
                null);
        if (course_publish == null) {
            XueChengPlusException.cast(CommonError.UNKOWN_ERROR);
        }

    }

    /**
     * 保存发布信息
     *
     * @param courseId
     */
    private void saveCoursePublish(Long courseId) {
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        CoursePublish coursePublishDB = coursePublishMapper.selectById(courseId);
        CourseBase courseBase = courseBaseInfoMapper.selectById(courseId);
        CoursePublish coursePublish = new CoursePublish();
        BeanUtils.copyProperties(coursePublishPre, coursePublish);
        coursePublish.setStatus("202004");
        coursePublish.setOnlineDate(LocalDateTime.now());
        //插入发布表，更新状态
        if (coursePublishDB == null) {
            int insert = coursePublishMapper.insert(coursePublish);
            if (insert <= 0) {
                XueChengPlusException.cast("课程发布失败");
            }
        } else {
            //如果已发布，直接更新
            coursePublishMapper.updateById(coursePublish);
        }
        //更新课程审核和发布状态
        courseBase.setAuditStatus("202004");
        courseBase.setStatus("203002");
        int i = courseBaseInfoMapper.updateById(courseBase);
        if (i <= 0) {
            XueChengPlusException.cast("更新课程状态失败，发布课程失败");
        }

    }


}
